const { Op } = require('sequelize');
const { Product, Order, OrderItem, sequelize } = require('../models');
const logger = require('../utils/logger');

class ProductManagementService {
  /**
   * 获取商品列表（管理后台）
   */
  async getProductList(options = {}) {
    try {
      const {
        page = 1,
        limit = 20,
        search,
        category,
        type,
        status,
        isHot,
        isNew,
        isFeatured,
        isPointsProduct,
        stockStatus, // 'in_stock', 'low_stock', 'out_of_stock'
        sortBy = 'createdAt',
        sortOrder = 'DESC'
      } = options;

      const where = {};
      
      // 搜索条件
      if (search) {
        where[Op.or] = [
          { name: { [Op.like]: `%${search}%` } },
          { description: { [Op.like]: `%${search}%` } }
        ];
      }

      // 筛选条件
      if (category) where.categoryId = category;
      if (type) where.type = type;
      if (status !== undefined) where.status = parseInt(status);
      if (isHot !== undefined) where.isHot = isHot === 'true';
      if (isNew !== undefined) where.isNew = isNew === 'true';
      if (isFeatured !== undefined) where.isFeatured = isFeatured === 'true';
      if (isPointsProduct !== undefined) where.isPointsProduct = isPointsProduct === 'true';

      // 库存状态筛选
      if (stockStatus) {
        switch (stockStatus) {
          case 'out_of_stock':
            where.stock = 0;
            break;
          case 'low_stock':
            where.stock = { [Op.between]: [1, 10] };
            break;
          case 'in_stock':
            where.stock = { [Op.gt]: 10 };
            break;
        }
      }

      const { count, rows } = await Product.findAndCountAll({
        where,
        limit: parseInt(limit),
        offset: (parseInt(page) - 1) * parseInt(limit),
        order: [[sortBy, sortOrder.toUpperCase()]],
        include: [
          {
            model: OrderItem,
            as: 'orderItems',
            attributes: [],
            required: false
          }
        ],
        attributes: {
          include: [
            [
              sequelize.fn('COALESCE', sequelize.fn('SUM', sequelize.col('orderItems.quantity')), 0),
              'totalSales'
            ]
          ]
        },
        group: ['Product.id'],
        subQuery: false
      });

      return {
        products: rows,
        pagination: {
          current: parseInt(page),
          total: Math.ceil(count.length / limit),
          pageSize: parseInt(limit),
          totalItems: count.length
        }
      };
    } catch (error) {
      logger.error('Get product list failed:', error);
      throw error;
    }
  }

  /**
   * 获取商品详情（管理后台）
   */
  async getProductById(productId) {
    try {
      const product = await Product.findByPk(productId, {
        include: [
          {
            model: OrderItem,
            as: 'orderItems',
            include: [
              {
                model: Order,
                attributes: ['id', 'status', 'createdAt']
              }
            ]
          }
        ]
      });

      if (!product) {
        throw new Error('商品不存在');
      }

      // 计算销售统计
      const salesStats = await this.getProductSalesStats(productId);

      return {
        product,
        salesStats
      };
    } catch (error) {
      logger.error('Get product by id failed:', error);
      throw error;
    }
  }

  /**
   * 创建商品
   */
  async createProduct(productData, operatorId) {
    try {
      const {
        name,
        description,
        price,
        originalPrice,
        coverImage,
        images,
        categoryId,
        type,
        specifications,
        stock,
        pointsReward,
        pointsPrice,
        isPointsProduct,
        isFeatured,
        isNew,
        isHot,
        sortOrder,
        status = 1
      } = productData;

      // 验证必填字段
      if (!name || !price) {
        throw new Error('商品名称和价格不能为空');
      }

      if (price <= 0) {
        throw new Error('商品价格必须大于0');
      }

      if (stock < 0) {
        throw new Error('库存数量不能为负数');
      }

      const product = await Product.create({
        name,
        description,
        price,
        originalPrice,
        coverImage,
        images,
        categoryId,
        type,
        specifications,
        stock,
        pointsReward: pointsReward || 0,
        pointsPrice,
        isPointsProduct: isPointsProduct || false,
        isFeatured: isFeatured || false,
        isNew: isNew || false,
        isHot: isHot || false,
        sortOrder: sortOrder || 0,
        status
      });

      logger.info(`管理员 ${operatorId} 创建了商品 ${product.id}`);

      return product;
    } catch (error) {
      logger.error('Create product failed:', error);
      throw error;
    }
  }

  /**
   * 更新商品
   */
  async updateProduct(productId, updateData, operatorId) {
    try {
      const product = await Product.findByPk(productId);
      
      if (!product) {
        throw new Error('商品不存在');
      }

      const {
        name,
        description,
        price,
        originalPrice,
        coverImage,
        images,
        categoryId,
        type,
        specifications,
        stock,
        pointsReward,
        pointsPrice,
        isPointsProduct,
        isFeatured,
        isNew,
        isHot,
        sortOrder,
        status
      } = updateData;

      // 验证价格
      if (price !== undefined && price <= 0) {
        throw new Error('商品价格必须大于0');
      }

      // 验证库存
      if (stock !== undefined && stock < 0) {
        throw new Error('库存数量不能为负数');
      }

      await product.update({
        name: name || product.name,
        description: description !== undefined ? description : product.description,
        price: price !== undefined ? price : product.price,
        originalPrice: originalPrice !== undefined ? originalPrice : product.originalPrice,
        coverImage: coverImage !== undefined ? coverImage : product.coverImage,
        images: images !== undefined ? images : product.images,
        categoryId: categoryId !== undefined ? categoryId : product.categoryId,
        type: type || product.type,
        specifications: specifications !== undefined ? specifications : product.specifications,
        stock: stock !== undefined ? stock : product.stock,
        pointsReward: pointsReward !== undefined ? pointsReward : product.pointsReward,
        pointsPrice: pointsPrice !== undefined ? pointsPrice : product.pointsPrice,
        isPointsProduct: isPointsProduct !== undefined ? isPointsProduct : product.isPointsProduct,
        isFeatured: isFeatured !== undefined ? isFeatured : product.isFeatured,
        isNew: isNew !== undefined ? isNew : product.isNew,
        isHot: isHot !== undefined ? isHot : product.isHot,
        sortOrder: sortOrder !== undefined ? sortOrder : product.sortOrder,
        status: status !== undefined ? status : product.status
      });

      logger.info(`管理员 ${operatorId} 更新了商品 ${productId}`);

      return product;
    } catch (error) {
      logger.error('Update product failed:', error);
      throw error;
    }
  }

  /**
   * 删除商品
   */
  async deleteProduct(productId, operatorId) {
    try {
      const product = await Product.findByPk(productId);
      
      if (!product) {
        throw new Error('商品不存在');
      }

      // 检查是否有未完成的订单
      const pendingOrders = await OrderItem.count({
        include: [
          {
            model: Order,
            where: {
              status: { [Op.in]: ['pending', 'processing'] }
            }
          }
        ],
        where: { productId }
      });

      if (pendingOrders > 0) {
        throw new Error('该商品有未完成的订单，无法删除');
      }

      await product.destroy();

      logger.info(`管理员 ${operatorId} 删除了商品 ${productId}`);

      return true;
    } catch (error) {
      logger.error('Delete product failed:', error);
      throw error;
    }
  }

  /**
   * 批量更新商品状态
   */
  async batchUpdateProducts(productIds, updateData, operatorId) {
    const transaction = await sequelize.transaction();
    
    try {
      const { status, isFeatured, isHot, isNew } = updateData;
      const updateFields = {};

      if (status !== undefined) updateFields.status = status;
      if (isFeatured !== undefined) updateFields.isFeatured = isFeatured;
      if (isHot !== undefined) updateFields.isHot = isHot;
      if (isNew !== undefined) updateFields.isNew = isNew;

      await Product.update(updateFields, {
        where: {
          id: { [Op.in]: productIds }
        },
        transaction
      });

      await transaction.commit();

      logger.info(`管理员 ${operatorId} 批量更新了 ${productIds.length} 个商品`);

      return true;
    } catch (error) {
      await transaction.rollback();
      logger.error('Batch update products failed:', error);
      throw error;
    }
  }

  /**
   * 库存管理 - 调整库存
   */
  async adjustStock(productId, adjustment, reason, operatorId) {
    try {
      const product = await Product.findByPk(productId);
      
      if (!product) {
        throw new Error('商品不存在');
      }

      const newStock = product.stock + adjustment;
      
      if (newStock < 0) {
        throw new Error('调整后库存不能为负数');
      }

      await product.update({ stock: newStock });

      // 这里可以记录库存变动日志
      logger.info(`管理员 ${operatorId} 调整商品 ${productId} 库存：${adjustment}，原因：${reason}`);

      return {
        productId,
        oldStock: product.stock,
        newStock,
        adjustment,
        reason
      };
    } catch (error) {
      logger.error('Adjust stock failed:', error);
      throw error;
    }
  }

  /**
   * 库存预警 - 获取低库存商品
   */
  async getLowStockProducts(threshold = 10) {
    try {
      const products = await Product.findAll({
        where: {
          status: 1,
          stock: { [Op.lte]: threshold }
        },
        order: [['stock', 'ASC']],
        attributes: ['id', 'name', 'stock', 'coverImage']
      });

      return products;
    } catch (error) {
      logger.error('Get low stock products failed:', error);
      throw error;
    }
  }

  /**
   * 获取商品销售统计
   */
  async getProductSalesStats(productId, days = 30) {
    try {
      const startDate = new Date(Date.now() - days * 24 * 60 * 60 * 1000);

      const [
        totalSales,
        recentSales,
        totalRevenue,
        recentRevenue
      ] = await Promise.all([
        OrderItem.sum('quantity', {
          where: { productId },
          include: [
            {
              model: Order,
              where: { status: 'completed' }
            }
          ]
        }) || 0,

        OrderItem.sum('quantity', {
          where: { productId },
          include: [
            {
              model: Order,
              where: {
                status: 'completed',
                createdAt: { [Op.gte]: startDate }
              }
            }
          ]
        }) || 0,

        OrderItem.sum('price', {
          where: { productId },
          include: [
            {
              model: Order,
              where: { status: 'completed' }
            }
          ]
        }) || 0,

        OrderItem.sum('price', {
          where: { productId },
          include: [
            {
              model: Order,
              where: {
                status: 'completed',
                createdAt: { [Op.gte]: startDate }
              }
            }
          ]
        }) || 0
      ]);

      return {
        totalSales,
        recentSales,
        totalRevenue,
        recentRevenue,
        period: `${days}天`
      };
    } catch (error) {
      logger.error('Get product sales stats failed:', error);
      throw error;
    }
  }

  /**
   * 商品统计概览
   */
  async getProductOverview() {
    try {
      const [
        totalProducts,
        activeProducts,
        inactiveProducts,
        lowStockProducts,
        outOfStockProducts,
        hotProducts,
        newProducts,
        pointsProducts
      ] = await Promise.all([
        Product.count(),
        Product.count({ where: { status: 1 } }),
        Product.count({ where: { status: 0 } }),
        Product.count({ where: { status: 1, stock: { [Op.lte]: 10 } } }),
        Product.count({ where: { status: 1, stock: 0 } }),
        Product.count({ where: { status: 1, isHot: true } }),
        Product.count({ where: { status: 1, isNew: true } }),
        Product.count({ where: { status: 1, isPointsProduct: true } })
      ]);

      return {
        totalProducts,
        activeProducts,
        inactiveProducts,
        lowStockProducts,
        outOfStockProducts,
        hotProducts,
        newProducts,
        pointsProducts
      };
    } catch (error) {
      logger.error('Get product overview failed:', error);
      throw error;
    }
  }

  /**
   * 价格管理 - 批量调价
   */
  async batchUpdatePrices(priceUpdates, operatorId) {
    const transaction = await sequelize.transaction();
    
    try {
      for (const update of priceUpdates) {
        const { productId, price, originalPrice } = update;
        
        await Product.update(
          { price, originalPrice },
          {
            where: { id: productId },
            transaction
          }
        );
      }

      await transaction.commit();

      logger.info(`管理员 ${operatorId} 批量调整了 ${priceUpdates.length} 个商品的价格`);

      return true;
    } catch (error) {
      await transaction.rollback();
      logger.error('Batch update prices failed:', error);
      throw error;
    }
  }

  /**
   * 促销管理 - 设置促销商品
   */
  async setPromotionProducts(productIds, promotionData, operatorId) {
    const transaction = await sequelize.transaction();
    
    try {
      const { isHot, isFeatured, isNew, originalPrice } = promotionData;
      
      await Product.update(
        {
          isHot: isHot !== undefined ? isHot : false,
          isFeatured: isFeatured !== undefined ? isFeatured : false,
          isNew: isNew !== undefined ? isNew : false,
          originalPrice: originalPrice !== undefined ? originalPrice : null
        },
        {
          where: { id: { [Op.in]: productIds } },
          transaction
        }
      );

      await transaction.commit();

      logger.info(`管理员 ${operatorId} 设置了 ${productIds.length} 个商品的促销信息`);

      return true;
    } catch (error) {
      await transaction.rollback();
      logger.error('Set promotion products failed:', error);
      throw error;
    }
  }

  /**
   * 导出商品数据
   */
  async exportProducts(options = {}) {
    try {
      const {
        search,
        category,
        type,
        status,
        stockStatus
      } = options;

      const where = {};
      
      if (search) {
        where[Op.or] = [
          { name: { [Op.like]: `%${search}%` } },
          { description: { [Op.like]: `%${search}%` } }
        ];
      }

      if (category) where.categoryId = category;
      if (type) where.type = type;
      if (status !== undefined) where.status = parseInt(status);

      if (stockStatus) {
        switch (stockStatus) {
          case 'out_of_stock':
            where.stock = 0;
            break;
          case 'low_stock':
            where.stock = { [Op.between]: [1, 10] };
            break;
          case 'in_stock':
            where.stock = { [Op.gt]: 10 };
            break;
        }
      }

      const products = await Product.findAll({
        where,
        order: [['createdAt', 'DESC']]
      });

      // 格式化导出数据
      const exportData = products.map(product => ({
        ID: product.id,
        商品名称: product.name,
        价格: product.price,
        原价: product.originalPrice || '',
        库存: product.stock,
        销量: product.sales,
        类型: product.type || '',
        状态: product.status === 1 ? '上架' : '下架',
        热门: product.isHot ? '是' : '否',
        新品: product.isNew ? '是' : '否',
        推荐: product.isFeatured ? '是' : '否',
        积分商品: product.isPointsProduct ? '是' : '否',
        创建时间: product.createdAt
      }));

      return exportData;
    } catch (error) {
      logger.error('Export products failed:', error);
      throw error;
    }
  }
}

module.exports = new ProductManagementService();